<template>
  <div class="store-name-container">
    <el-card class="setting-card">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><Shop /></el-icon>
          <span>本店名称设置</span>
        </div>
      </template>
      
      <div class="setting-content">
        <div class="description">
          <p>在这里您可以设置您的餐厅名称，这个名称将会显示在顾客的点餐界面上。请确保名称准确、吸引人，体现您餐厅的特色。</p>
        </div>
        
        <el-form
          ref="storeFormRef"
          :model="storeForm"
          :rules="storeRules"
          label-position="top"
          class="setting-form"
        >
          <el-form-item label="餐厅名称" prop="storeName">
            <el-input
              v-model="storeForm.storeName"
              placeholder="请输入您的餐厅名称"
              size="large"
              clearable
              maxlength="50"
              show-word-limit
            >
              <template #prefix>
                <el-icon><Shop /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item label="餐厅简介（可选）" prop="storeDescription">
            <el-input
              v-model="storeForm.storeDescription"
              type="textarea"
              placeholder="请输入餐厅简介，让顾客更好地了解您的餐厅"
              :rows="4"
              maxlength="200"
              show-word-limit
              resize="none"
            />
          </el-form-item>
        </el-form>
        
        <div class="action-buttons">
          <el-button size="large" @click="resetForm">重置</el-button>
          <el-button
            type="primary"
            size="large"
            :loading="saving"
            @click="saveStoreName"
          >
            保存设置
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, type FormInstance } from 'element-plus'
import { Shop } from '@element-plus/icons-vue'
import axios from 'axios'

const storeFormRef = ref<FormInstance>()
const saving = ref(false)

const storeForm = reactive({
  storeName: '',
  storeDescription: ''
})

const storeRules = {
  storeName: [
    { required: true, message: '请输入餐厅名称', trigger: 'blur' },
    { min: 2, max: 50, message: '餐厅名称长度在2到50个字符', trigger: 'blur' }
  ],
  storeDescription: [
    { max: 200, message: '简介不能超过200个字符', trigger: 'blur' }
  ]
}

// 发送请求到后端的函数
const sendStoreInfoToBackend = async (storeData: any) => {
  try {
    // 获取登录token和用户名
    const token = localStorage.getItem('token')
    const username = localStorage.getItem('username')
    
    const response = await axios.post('/systemSettings/add', {
      paramKey: "restaurantName",
      paramValue: storeData.storeName || '',
      description: storeData.storeDescription,
      createPeople: username
    }, {
      headers: {
        'Content-Type': 'application/json',
        ...(token && { 'Authorization': `Bearer ${token}` })
      }
    })
    
    const { code, message, data } = response.data;

    if (code !== 200) {
      console.error('请求失败:', message)
      return {
        success: false,
        code: code,
        message: message || '保存失败'
      }
    } else {
      return {
        success: true,
        code: code,
        message: message || '餐厅信息保存成功！',
        data: data || null
      }
    }
  } catch (error: any) {
    console.error('请求失败:', error)
    
    // 处理axios错误
    if (error.response) {
      const status = error.response.status
      let errorMessage = '请求失败'
      
      if (status === 403) {
        errorMessage = '权限不足，请重新登录'
      } else if (status === 401) {
        errorMessage = '登录已过期，请重新登录'
      } else if (status === 404) {
        errorMessage = '接口不存在'
      } else {
        errorMessage = `服务器错误：${status}`
      }
      
      return {
        success: false,
        message: errorMessage
      }
    } else if (error.request) {
      return {
        success: false,
        message: '网络连接失败，请检查网络'
      }
    } else {
      return {
        success: false,
        message: error.message || '未知错误'
      }
    }
  }
}

const saveStoreName = async () => {
  if (!storeFormRef.value) return
  
  const valid = await storeFormRef.value.validate().catch(() => false)
  if (!valid) return
  
  saving.value = true
  
  try {
    // 发送请求到后端
    const result = await sendStoreInfoToBackend(storeForm)
    
    if (result?.success) {
      ElMessage.success(result.message);
      
      // 保存成功后清空表单内容
      storeForm.storeName = '';
      storeForm.storeDescription = '';
      
      // 清除表单验证状态
      if (storeFormRef.value) {
        storeFormRef.value.clearValidate()
      }
      
      // 可选：清除本地存储
      localStorage.removeItem('storeInfo')
      
    } else {
      ElMessage.error(result?.message || '保存失败，请重试')
    }
    
  } catch (error) {
    console.error('保存过程中发生错误:', error)
    ElMessage.error('保存过程中发生错误，请重试')
  } finally {
    saving.value = false
  }
}

const resetForm = () => {
  if (storeFormRef.value) {
    storeFormRef.value.resetFields()
  }
}

onMounted(() => {
  // 从本地存储加载已保存的信息
  const savedInfo = localStorage.getItem('storeInfo')
  if (savedInfo) {
    try {
      const parsedInfo = JSON.parse(savedInfo)
      Object.assign(storeForm, parsedInfo)
    } catch (error) {
      console.error('加载保存的信息失败:', error)
    }
  }
})
</script>

<style scoped>
.store-name-container {
  max-width: 800px;
  margin: 0 auto;
}

.setting-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: 600;
  color: #303133;
  font-size: 18px;
}

.header-icon {
  margin-right: 8px;
  color: #409eff;
  font-size: 20px;
}

.setting-content {
  padding: 20px 0;
}

.description {
  background: #f8f9fa;
  border-left: 4px solid #409eff;
  padding: 16px 20px;
  margin-bottom: 30px;
  border-radius: 0 8px 8px 0;
}

.description p {
  margin: 0;
  color: #606266;
  line-height: 1.6;
}

.setting-form {
  margin-bottom: 30px;
}

.setting-form .el-form-item {
  margin-bottom: 24px;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .store-name-container {
    padding: 0 16px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
}
</style> 